package net.java.nioserver.sample;

import net.java.nioserver.operations.OpRead;
import net.java.nioserver.operations.AbstractOperation;
import net.java.nioserver.utils.ChannelUtil;
import net.java.nioserver.utils.Pool;
import net.jcip.annotations.ThreadSafe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author Leonid Shlyapnikov
 */
@ThreadSafe
public class EchoOpRead extends AbstractOperation implements OpRead {

    public EchoOpRead(Pool<ByteBuffer> byteBufferPool) {
        super(byteBufferPool);
    }

    public boolean handle(SocketChannel sc) throws IOException, InterruptedException {
        final ByteBuffer buffer = byteBufferPool.take();
        try {
            boolean runMore = ChannelUtil.readOneLineFromChannel(sc, buffer);
            if (!runMore) {
                return false; // far end disconnected, cannot send anything back
            }
            buffer.flip();
            ChannelUtil.writeToChannel(buffer, sc);

            return runMore;
        } finally {
            byteBufferPool.release(buffer);
        }
    }
}
